package com.laoba.meishijia.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 登录拦截器
 */
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 前置方法
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断是否登录
        //判断session
        //没有登录重定向到登录页面、登录了，定向到index页面

        //先去获取session对象
        HttpSession session = request.getSession();

        //获取登录的标记
        String adminName = (String) session.getAttribute("adminName");
        //判断session的值是否为null
        if (adminName == null) {
            //如果没有登录，这里就产生了循环，因为默认是拦截所有请求，所以就变成了无限次的重定向，
            //浏览器出现了too many redirect
            response.sendRedirect("/login/page");
            return false;
        }
        return true;//false拦截、true放行
    }

    /**
     * 后置方法
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
